﻿// (c) Copyright Fernando Cerqueira.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Microsoft.VisualStudio.PlatformUI;
using AppRes = WindowsPhoneCommands.Resources;
using System.Net;

// ReSharper disable CheckNamespace
namespace WindowsPhoneCommands
// ReSharper restore CheckNamespace
{
    /// <summary>
    /// Interaction logic for XapDeploy.xaml
    /// </summary>
    // ReSharper disable RedundantExtendsListEntry
    public partial class UserSettingsDialog : DialogWindow
    // ReSharper restore RedundantExtendsListEntry
    {
        private bool _loaded;

        public UserSettingsDialog()
        {
            InitializeComponent();
            Background = VsTheming.GetDialogBackground();
            Foreground = VsTheming.GetWindowText();
            Loaded += UserSettingsDialogLoaded;
        }

        private void UserSettingsDialogLoaded(object sender, RoutedEventArgs e)
        {
            if (!_loaded)
            {
                Title = AppRes.ToolWindowTitle + " " + AppRes.XTitDialogUserSettings;
                UserSettings.ReLoad();
                ReadSettings();
            }
            _loaded = true;
        }

        private  void ReadSettings()
        {
            OptGoogle.IsChecked = false;
            OptBing.IsChecked = false;
            switch (UserSettings.Current.EngineTranslate)
            {
                case EngineTranslate.Google:
                    OptGoogle.IsChecked = true;
                    break;
                case EngineTranslate.Bing:
                    OptBing.IsChecked = true;
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
            ChkCloseXde.IsChecked = UserSettings.Current.CloseXde;
            ChkPromptPwd.IsChecked = UserSettings.Current.PromptPwd;
            BntVld.IsEnabled = true;
            BntEncry.IsEnabled = false;
            BntReset.IsEnabled = true;
            BoxGoogle.IsEnabled = false;
            TxtGoogleUrl.Text = UserSettings.Current.UrlGoogle;
            TxtGoogleFindField.Text = UserSettings.Current.FindjsonGoogle;
            BoxBing.IsEnabled = false;
            TxtBingClientId.Text = UserSettings.Current.BingClientId;
            TxtBingSecret.Text = UserSettings.Current.BingSecretCode;

            ChkDefaultCred.IsChecked = true;

            TxtServerPort.Text = UserSettings.Current.ProxyAddressAndPort;
            TxtDomain.Text = UserSettings.Current.ProxyUserDomain;
            TxtUser.Text = UserSettings.Current.ProxyUserName;
            TxtPwdProxy.Password = EncryptDecryptMd5.DecryptString(UserSettings.Current.ProxyPassword, EncryptDecryptMd5.DecryptString(UserSettings.Current.Md5Password, Constants.GuidRef));
            TxtServerPort.IsEnabled = false;
            TxtDomain.IsEnabled = false;
            TxtUser.IsEnabled = false;
            TxtPwdProxy.IsEnabled = false;
            BntTestConn.IsEnabled = true;
        }

        private void BntOkClick(object sender, RoutedEventArgs e)
        {
            if (ValidateFields(-1,true))
            {
                // ReSharper disable PossibleInvalidOperationException
                UserSettings.Current.CloseXde = ChkCloseXde.IsChecked.Value;
                // ReSharper restore PossibleInvalidOperationException
                UserSettings.Current.EngineTranslate = OptBing.IsChecked != null && OptBing.IsChecked.Value ? EngineTranslate.Bing : EngineTranslate.Google;
                if (BntEncry.IsEnabled)
                {
                    BntEncry.IsEnabled = false;
                    TxtBingClientId.Text = EncryptDecryptMd5.EncryptString(TxtBingClientId.Text, EncryptDecryptMd5.DecryptString(UserSettings.Current.Md5Password, Constants.GuidRef));
                    TxtBingSecret.Text = EncryptDecryptMd5.EncryptString(TxtBingSecret.Text, EncryptDecryptMd5.DecryptString(UserSettings.Current.Md5Password, Constants.GuidRef));
                    TxtGoogleUrl.Text = EncryptDecryptMd5.EncryptString(TxtGoogleUrl.Text, EncryptDecryptMd5.DecryptString(UserSettings.Current.Md5Password, Constants.GuidRef));
                    TxtGoogleFindField.Text = EncryptDecryptMd5.EncryptString(TxtGoogleFindField.Text, EncryptDecryptMd5.DecryptString(UserSettings.Current.Md5Password, Constants.GuidRef));
                }
                UserSettings.Current.UrlGoogle = TxtGoogleUrl.Text;
                UserSettings.Current.FindjsonGoogle = TxtGoogleFindField.Text;
                UserSettings.Current.BingClientId = TxtBingClientId.Text;
                UserSettings.Current.BingSecretCode= TxtBingSecret.Text;
                if (ChkPromptPwd.IsChecked != null)
                {
                    UserSettings.Current.PromptPwd = ChkPromptPwd.IsChecked.Value;

                    if (ChkDefaultCred.IsChecked != null && ChkDefaultCred.IsChecked.Value)
                    {
                        UserSettings.Current.ProxyAddressAndPort = string.Empty;
                        UserSettings.Current.ProxyUserDomain = string.Empty;
                        UserSettings.Current.ProxyUserName = string.Empty;
                        UserSettings.Current.ProxyPassword = string.Empty;
                    }
                    else
                    {
                        UserSettings.Current.ProxyAddressAndPort = TxtServerPort.Text;
                        UserSettings.Current.ProxyUserDomain = TxtDomain.Text;
                        UserSettings.Current.ProxyUserName = TxtUser.Text;
                        UserSettings.Current.ProxyPassword = EncryptDecryptMd5.EncryptString(TxtPwdProxy.Password, EncryptDecryptMd5.DecryptString(UserSettings.Current.Md5Password, Constants.GuidRef));
                    }
                }
                UserSettings.Save();

                BoxBing.IsEnabled = false;
                BoxGoogle.IsEnabled = false;
                BntEncry.IsEnabled = false;
                BntVld.IsEnabled = true;

                Close();
            }
        }

        private static int Adorne(Control control, bool error, string tootip)
        {
            if (error)
            {
                var colorerr = VsTheming.GetColorError();
                if (!control.BorderBrush.Equals(colorerr))
                {
                    control.Tag = control.BorderBrush;
                    control.BorderBrush = colorerr;
                    control.ToolTip = tootip;
                }
            }
            else
            {
                if (!control.BorderBrush.Equals(control.Tag) && control.Tag != null)
                {
                    control.BorderBrush = (Brush)control.Tag;
                }
            }
            return error ? 1 : 0;
        }

        private bool ValidateFields(int tab, bool showmsg)
        {
            var qtd = 0;
            if (tab == 1 || tab < 0)
            {
                if (!string.IsNullOrEmpty(TxtBingClientId.Text.Trim()) || !string.IsNullOrEmpty(TxtBingSecret.Text.Trim()))
                {
                    qtd += Adorne(TxtBingClientId, string.IsNullOrEmpty(TxtBingClientId.Text.Trim()), AppRes.RequiredField);
                    qtd += Adorne(TxtBingSecret, string.IsNullOrEmpty(TxtBingSecret.Text.Trim()), AppRes.RequiredField);
                }
                if (!string.IsNullOrEmpty(TxtGoogleUrl.Text.Trim()) || !string.IsNullOrEmpty(TxtGoogleFindField.Text.Trim()))
                {
                    qtd += Adorne(TxtGoogleUrl, string.IsNullOrEmpty(TxtGoogleUrl.Text.Trim()), AppRes.RequiredField);
                    qtd += Adorne(TxtGoogleFindField, string.IsNullOrEmpty(TxtGoogleFindField.Text.Trim()), AppRes.RequiredField);
                }
            }
            if (tab == 2 || tab < 0)
            {
                // ReSharper disable PossibleInvalidOperationException
                if (!ChkDefaultCred.IsChecked.Value)
                // ReSharper restore PossibleInvalidOperationException
                {
                    qtd += Adorne(TxtServerPort, string.IsNullOrEmpty(TxtServerPort.Text.Trim()), AppRes.RequiredField);
                    qtd += Adorne(TxtDomain, string.IsNullOrEmpty(TxtDomain.Text.Trim()), AppRes.RequiredField);
                    qtd += Adorne(TxtUser, string.IsNullOrEmpty(TxtUser.Text.Trim()), AppRes.RequiredField);
                    qtd += Adorne(TxtPwdProxy, string.IsNullOrEmpty(TxtPwdProxy.Password.Trim()), AppRes.RequiredField);
                }
            }
            if (qtd > 0 && showmsg)
            {
                MessageBox.Show(AppRes.ErrCompleteFields, AppRes.ToolWindowTitle, MessageBoxButton.OK,MessageBoxImage.Error);
            }
            return (qtd == 0);
        }

        private void ChkDefaultCredClick(object sender, RoutedEventArgs e)
        {
            // ReSharper disable PossibleInvalidOperationException
            TxtServerPort.IsEnabled = !ChkDefaultCred.IsChecked.Value;
            TxtDomain.IsEnabled = !ChkDefaultCred.IsChecked.Value;
            TxtUser.IsEnabled = !ChkDefaultCred.IsChecked.Value;
            TxtPwdProxy.IsEnabled = !ChkDefaultCred.IsChecked.Value;
            if (!ChkDefaultCred.IsChecked.Value)
            {
                ValidateFields(2, false);
            }
            // ReSharper restore PossibleInvalidOperationException
        }

        private void BntVldClick(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(TxtPwd.Password))
            {
                MessageBox.Show(AppRes.PwdEmpty, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Warning);
                TxtPwd.Focus();
                return;
            }
            if (BntReset.Tag != null && BntReset.Tag.ToString() == "NEW")
            {
                BntReset.Tag = null;
                BntReset.IsEnabled = true;
                UserSettings.Current.Md5Password = EncryptDecryptMd5.EncryptString(TxtPwd.Password, Constants.GuidRef);
                UserSettings.Current.UrlGoogle = null;
                UserSettings.Current.FindjsonGoogle = null;
                UserSettings.Current.BingClientId = null;
                UserSettings.Current.BingSecretCode = null;
            }
            if (TxtPwd.Password != EncryptDecryptMd5.DecryptString(UserSettings.Current.Md5Password, Constants.GuidRef))
            {
                MessageBox.Show(AppRes.InvalidPwd, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Warning);
                TxtPwd.Focus();
                return;
            }
            BntVld.IsEnabled = false;
            BntEncry.IsEnabled = true;
            BoxBing.IsEnabled = true;
            TxtBingClientId.Text = EncryptDecryptMd5.DecryptString(UserSettings.Current.BingClientId, EncryptDecryptMd5.DecryptString(UserSettings.Current.Md5Password, Constants.GuidRef));
            TxtBingSecret.Text = EncryptDecryptMd5.DecryptString(UserSettings.Current.BingSecretCode, EncryptDecryptMd5.DecryptString(UserSettings.Current.Md5Password, Constants.GuidRef));
            BoxGoogle.IsEnabled = true;
            TxtGoogleUrl.Text = EncryptDecryptMd5.DecryptString(UserSettings.Current.UrlGoogle, EncryptDecryptMd5.DecryptString(UserSettings.Current.Md5Password, Constants.GuidRef));
            TxtGoogleFindField.Text = EncryptDecryptMd5.DecryptString(UserSettings.Current.FindjsonGoogle, EncryptDecryptMd5.DecryptString(UserSettings.Current.Md5Password, Constants.GuidRef));
        }

        private void Resetfieldstranslate()
        {
            UserSettings.Current.UrlGoogle = null;
            UserSettings.Current.FindjsonGoogle = null;
            UserSettings.Current.BingClientId = null;
            UserSettings.Current.BingSecretCode = null;

            BoxGoogle.IsEnabled = false;
            TxtGoogleUrl.Text = UserSettings.Current.UrlGoogle;
            TxtGoogleFindField.Text = UserSettings.Current.FindjsonGoogle;
            BoxBing.IsEnabled = false;
            TxtBingClientId.Text = UserSettings.Current.BingClientId;
            TxtBingSecret.Text = UserSettings.Current.BingSecretCode;

            BntVld.IsEnabled = true;
            BntEncry.IsEnabled = false;
        }

        private void TxtBingClientIdLostFocus(object sender, RoutedEventArgs e)
        {
            ValidateFields(1, false);
        }

        private void TxtBingSecretTextChanged(object sender, TextChangedEventArgs e)
        {
            ValidateFields(1, false);
        }

        private void TxtGoogleUrlLostFocus(object sender, RoutedEventArgs e)
        {
            ValidateFields(1, false);
        }

        private void TxtGoogleFindFieldLostFocus(object sender, RoutedEventArgs e)
        {
            ValidateFields(1, false);
        }

        private void BntEncryClick(object sender, RoutedEventArgs e)
        {
            TxtBingClientId.Text = EncryptDecryptMd5.EncryptString(TxtBingClientId.Text, EncryptDecryptMd5.DecryptString(UserSettings.Current.Md5Password, Constants.GuidRef));
            TxtBingSecret.Text = EncryptDecryptMd5.EncryptString(TxtBingSecret.Text, EncryptDecryptMd5.DecryptString(UserSettings.Current.Md5Password, Constants.GuidRef));
            TxtGoogleUrl.Text = EncryptDecryptMd5.EncryptString(TxtGoogleUrl.Text, EncryptDecryptMd5.DecryptString(UserSettings.Current.Md5Password, Constants.GuidRef));
            TxtGoogleFindField.Text = EncryptDecryptMd5.EncryptString(TxtGoogleFindField.Text, EncryptDecryptMd5.DecryptString(UserSettings.Current.Md5Password, Constants.GuidRef));
            BoxBing.IsEnabled = false;
            BoxGoogle.IsEnabled = false;
            BntEncry.IsEnabled = false;
            BntVld.IsEnabled = true;
            TxtPwd.Password = string.Empty;
            TxtPwd.Focus();
        }

        private void BntResetClick(object sender, RoutedEventArgs e)
        {
            var result = MessageBox.Show(AppRes.QResetPwd, AppRes.ToolWindowTitle, MessageBoxButton.YesNo,MessageBoxImage.Question);
            if (result == MessageBoxResult.No)
            {
                return;
            }
            Resetfieldstranslate();
            ValidateFields(-1, false);
            TxtPwd.Password = string.Empty;
            BntReset.Tag = "NEW";
            BntReset.IsEnabled = false;
            TxtPwd.Focus();
        }

        private void TxtServerPortLostFocus(object sender, RoutedEventArgs e)
        {
            ValidateFields(2, false);
        }

        private void TxtDomainLostFocus(object sender, RoutedEventArgs e)
        {
            ValidateFields(2, false);
        }

        private void TxtUserLostFocus(object sender, RoutedEventArgs e)
        {
            ValidateFields(2, false);
        }

        private void TxtPwdProxyLostFocus(object sender, RoutedEventArgs e)
        {
            ValidateFields(2, false);
        }

        private void BntTestConnClick(object sender, RoutedEventArgs e)
        {
            try
            {
                var request = (HttpWebRequest)WebRequest.Create(Constants.UrlTest);
                WebProxy proxy;
                if (ChkDefaultCred.IsChecked != null && !ChkDefaultCred.IsChecked.Value)
                {
                    proxy = TxtDomain.Text != null ?
                        new WebProxy(TxtServerPort.Text, true, null,
                            new NetworkCredential(TxtUser.Text, TxtPwdProxy.Password, TxtDomain.Text)) { UseDefaultCredentials = false } :
                        new WebProxy(TxtServerPort.Text, true, null,
                            new NetworkCredential(TxtUser.Text, TxtPwdProxy.Password)) { UseDefaultCredentials = false };
                }
                else
                {
                    proxy = new WebProxy { UseDefaultCredentials = true };
                }
                request.Proxy = proxy;
                bool ok;
                string urlresp;
                using (var response = request.GetResponse()) 
                {
                    urlresp = response.ResponseUri.AbsoluteUri;
                    ok = urlresp.StartsWith(Constants.UrlTest);
                }
                if (!ok)
                {
                    MessageBox.Show(string.Format(AppRes.TestConnProxyNOk, Constants.UrlTest, urlresp), AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    MessageBox.Show(AppRes.TestConnProxyOk, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, AppRes.ToolWindowTitle, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

    }
}
